package com.yg.utils;


import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class DownLoadUtil {

    /**
     * 模板文件下载
     *
     * @param response
     * @param writeExcelFilePath excel下载路径
     * @param fileName           文件名称
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String downLoadFile(HttpServletResponse response, String writeExcelFilePath, String fileName) throws UnsupportedEncodingException {
        if (fileName != null) {
            fileName = fileName + ".xlsx";
            //设置文件路径
            File file = new File(writeExcelFilePath, fileName);
            if (file.exists()) {
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
//                response.addHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "UTF-8"));// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }

}
